package com.zx._07_数据库.测试数据;

import com.github.javafaker.Faker;
import com.zx._07_数据库.jdbc.JDBC;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Locale;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SaveStudent {

    public static void save() {

        log.info("save Student begin");
        String sql = "INSERT INTO test.t_student (id, name, class_id) VALUES(?,?,?)";

        Faker fakerWithCN = new Faker(Locale.CHINA);// Locale.US  美国的数据

        Connection connection = JDBC.getConnection();
        PreparedStatement ps = null;
        try {
            ps = connection.prepareStatement(sql);
            int id = 1;
            int class_id = 1;
            int count = Config.STUDENT_COUNT;
            while (true) {
                int curCount = Math.min(count, Config.CLASS_STUDENT_COUNT);
                for (int i = 0; i < curCount; i++) {
                    ps.setInt(1, id);
                    ps.setString(2, fakerWithCN.name().fullName());
                    ps.setInt(3, class_id);
                    ps.addBatch();
                    id++;
                }

                class_id++;

                count -= Config.CLASS_STUDENT_COUNT;
                if (count <= 0) {
                    break;
                }
            }
            ps.executeBatch();
            log.info("save Student finsh");
        } catch (Exception e) {
            log.error("save Student error", e);
        } finally {
            JDBC.release(connection, ps, null);
        }
    }
}
